package net.shambolica.ember.tests.containers;

import net.shambolica.ember.utils.RuntimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;

/**
 * I am a servlet that checks whether paths can be easily mapped from within
 * a web container.
 */
public class PathTestServlet extends HttpServlet {

    private Logger log = LoggerFactory.getLogger(PathTestServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/plain");
        final PrintWriter out = resp.getWriter();

        showImmediatePaths(out);

        showContextPaths(req, out);

        showBasePaths(out);

        showLibPaths(out);

    }

    private void showContextPaths(HttpServletRequest req, PrintWriter out) throws IOException {
        out.println("context path = '"+req.getContextPath()+"'");
        out.println("classloader resource(\".\")='"+getClass().getClassLoader().getResource(".").getFile()+"'");
        for (Enumeration<URL> it = getClass().getClassLoader().getResources("") ; it.hasMoreElements() ; ) {
            URL url = it.nextElement();
            out.println("-> "+ url+" -> "+url.getPath());
        }
    }

    private void showImmediatePaths(PrintWriter out) throws IOException {
        File here = new File(".");
        File up = new File("..");

        out.println("path(\".\")='"+here.getCanonicalPath()+"'");
        out.println("path(\"..\")='"+up.getCanonicalPath()+"'");
    }

    private void showBasePaths(PrintWriter out) {
        List<String> basePaths = RuntimeUtils.getEmberPaths();
        out.println("ember base paths: "+basePaths.size());
        for (String path: basePaths) {
            out.println("-> "+path);
        }
    }

    private void showLibPaths(PrintWriter out) {
        List<String> libPaths = RuntimeUtils.getEmberLibPaths();
        out.println("ember lib paths: "+libPaths.size());
        for (String path: libPaths) {
            out.println("-> "+path);
        }
    }

}
